package com.albon.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;

public class JsonNetwork {
	private final String TAG = "JsonNetwork";
	ProgressDialog mProgressDialog;
	String postData;
	ArrayList<String> nameList = new ArrayList<String>();
	ArrayList<String> postList = new ArrayList<String>();
	String urlString;
	String dataType;
	StringBuffer json;
	Handler mNetWorkHandler;
	NetworkComplete mNetWorkComplete;
	Activity activity;
	boolean isShow=false;
	int errorCode = 0;

	public void setNetWorkComplete(NetworkComplete mNetWorkComplete){
		this.mNetWorkComplete = mNetWorkComplete;
	}

	public JsonNetwork(Activity activity, ArrayList<String> nameList, ArrayList<String> postList, String urlString, String dataType){
		this.activity = activity;
		this.nameList = nameList;
		this.postList = postList;
		this.urlString = urlString;
		this.dataType = dataType;
		Logg.d(TAG,"JasonNetWork create");
		mNetWorkHandler = new Handler()
		{
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if(msg.what==0)
				{
					if(mNetWorkComplete != null)
					{
						mNetWorkComplete.onNetWorkComplete(true, json.toString());
					}
				}
				if(msg.what==-1)
				{
					if(mNetWorkComplete != null)
					{
						mNetWorkComplete.onNetWorkComplete(false, null);
					}
				}
				if(msg.what==1)
				{
					if(mNetWorkComplete != null)
					{
						mNetWorkComplete.onNetWorkComplete(false, json.toString());
					}
				}
				if(mProgressDialog != null)
				{
					mProgressDialog.dismiss();
				}
				
			}

		};
	}

	public void setProgress(boolean isShow)
	{
		this.isShow = isShow;
	}

	public void onConnect()
	{
		boolean isDoubleClick = false;
		if(isDoubleClick) return;
		
		if(!isShow){
			mProgressDialog = null;
		}
		else{
			mProgressDialog = 
					ProgressDialog.show(activity, "","로딩중입니다.\n 잠시기다려 주세요.", true);
		}

		NetWorkThread mNetWorkThread = new NetWorkThread();
		mNetWorkThread.start();

	}

	public class NetWorkThread extends Thread
	{
		HttpURLConnection connection;
		public void run()
		{
			try 
			{
				if(dataType.equals(UrlList.GET))
				{
					String getData = "";
					for(int i=0;i<nameList.size();i++)
					{
						if(i==0){
							getData = nameList.get(i)+URLEncoder.encode(postList.get(i), "UTF-8");
						}
						else{
							getData = getData+"&"+nameList.get(i)+URLEncoder.encode(postList.get(i), "UTF-8");
						}
					}
					
					URL url = new URL(urlString+"?"+getData);
					Logg.e(TAG,"url : " + url);
					connection = (HttpURLConnection) url.openConnection();
					connection.setDoInput(true);
					connection.setUseCaches(false);
					connection.setRequestMethod(dataType);
					connection.setRequestProperty("Accept-Charset", HTTP.UTF_8);
					connection.setConnectTimeout(150000);
					connection.setReadTimeout(150000);
				}
				else if(dataType.equals(UrlList.POST))
				{
					URL url = new URL(urlString);
					Logg.e(TAG,"url : " + url);
					connection = (HttpURLConnection) url.openConnection();
					connection.setDoInput(true);
					connection.setDoOutput(true);
					connection.setUseCaches(false);
					connection.setRequestProperty("Accept-Charset", HTTP.UTF_8);
					connection.setRequestMethod(dataType);
					connection.setConnectTimeout(150000);
					connection.setReadTimeout(150000);
					if(nameList.isEmpty())
					{
						DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
						dos.writeBytes("");
						dos.flush();
						dos.close();
					}
					else 
					{
						DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
						for(int i=0;i<nameList.size();i++)
						{
							Logg.e(TAG,"param : " + nameList.get(i) + "("+ postList.get(i) +")");
							if(i==0){
								postData = nameList.get(i)+URLEncoder.encode(postList.get(i), "UTF-8");
							}
							else{
								postData = postData+"&"+nameList.get(i)+URLEncoder.encode(postList.get(i), "UTF-8");
							}
						}
						dos.writeBytes(postData);
						dos.flush();
						dos.close();
					}
				}

				Logg.e(TAG, connection.getResponseCode()+"<=========== Receive Before");
				
				errorCode = connection.getResponseCode();
				
				if(errorCode==403)
				{
					json = new StringBuffer();
					BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(),"UTF-8"));
					while(true)
					{
						String line = br.readLine();
						if(line == null) break;
						json.append(replace(line)+ '\n');
					}
					br.close();
					mNetWorkHandler.sendEmptyMessage(1);
				}
				else if(errorCode == 200)
				{
					
					json = new StringBuffer();
					BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
					while(true)
					{
						String line = br.readLine();
						if(line == null) break;
						json.append(replace(line)+ '\n');
					}
					br.close();
					mNetWorkHandler.sendEmptyMessage(0);
				}
				else
				{
					json = new StringBuffer();
					BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(),"UTF-8"));
					while(true)
					{
						String line = br.readLine();
						if(line == null) break;
						json.append(replace(line)+ '\n');
					}
					br.close();
					mNetWorkHandler.sendEmptyMessage(1);
				}
				
				Logg.e(TAG, connection.getResponseCode()+"<=========== Receive after" +
						"");
				Logg.e(TAG, "data :"+ json.toString());
			}
			catch (Exception ex) 
			{
				Logg.e(TAG, ex.toString());
				mNetWorkHandler.sendEmptyMessage(-1);
			}
			finally
			{
				connection.disconnect();
			}

		}
	}

	String replace(String someting)
	{
		return someting.replace("&amp;", "&");
	}

}
